
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from './../router'
import storage from './storage'

const TOKEN_ERROR = 'Token认证失败，请重新登录'
const DEFAULT_ERROR = '网络异常，请稍后重试'
let URL_PRO = ['/sys/login','/sys/logout']

const service = axios.create({
    baseURL: 'http://localhost:31750/',
    // baseURL: 'http://localhost:8801/',
    timeout: 8000
})

//请求拦截
service.interceptors.request.use((req) => {
    if (URL_PRO.includes(req.url)) {
        return req;
    }
    const headers = req.headers;
    const {token} = storage.getItem('userInfo')
    if (!headers.Authorization) {
        headers.Authorization = 'Bearer ' + token;
    }
    return req;
})

// 响应拦截
service.interceptors.response.use(
    response => {  //成功请求到数据
        return response.data;
        // const { code, result, message } = response.data;
        // if (code === 200) {
        //     ElMessage({
        //         message: message,
        //         type: 'success',
        //       })
        //     return result;
        // } else if (code === 40001) {
        //     ElMessage.error(TOKEN_ERROR);
        //     setTimeout(() => {
        //         router.push('/login');
        //     }, 15000);
        //     return Promise.reject(TOKEN_ERROR);
        // } else {
        //     ElMessage.error(message || DEFAULT_ERROR);
        //     return Promise.reject(message || DEFAULT_ERROR);
        // }
    },
    error => {  //响应错误处理
        const { code, result, message } = error.response.data;
        if (code === 200) {
            return result;
        } else if (code === 40001) {
            ElMessage.error(TOKEN_ERROR);
            setTimeout(() => {
                router.push('/login');
            }, 15000);
            return Promise.reject(TOKEN_ERROR);
        } else {
            ElMessage.error(message || DEFAULT_ERROR);
            return Promise.reject(message || DEFAULT_ERROR);
        }
    }
)


function request(options) {

    options.method = options.method || 'get';
    if (options.method.toLowerCase() === 'get') {
        options.params = options.data;
    }
    return service(options)
}

['get', 'post', 'put', 'delete', 'patch'].forEach((item) => {
    request[item] = (url, data, options) => {
        return request({
            url,
            data,
            method: item,
            ...options
        })
    }
})

export default request;